#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>

/* Send AT command('cmd') and check the modem's responds. 
    if modem's responds contains 'res', return 1 else 0 .
    When 'tms' millseconds passed, haven't received 'res',
    this function will exit and return 0 means false 

    when GPRS modem powered on, it will send some garbage information.
    eg: after sending [ATE0\r], data received from serial port:
    51,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,fffffff6,70,
    d,a,4d,4f,44,45,4d,3a,53,54,41,52,54,55,50,d,a, [garbage]
    41,54,45,30,d,d,a,4f,4b,d,a, [ATE0\r\r\nOK\r\n] */
static int at_command(int fd,const char *cmd,
                const char *res,int resLen,int tms)
{
    char buf[256];
    int num,index=0;
    fd_set readfds;
    struct timeval tv;

    if(!cmd) return 0;
    write(fd,cmd,strlen(cmd)); /* send command */
    if(!res) return 0;

    /* read responds and checked */
    FD_ZERO(&readfds);
    FD_SET(fd,&readfds);
    tv.tv_sec= (tms/1000); /* get seconds part */
    tv.tv_usec=(tms%1000)*1000; /* get microseconds part */

    while(index<sizeof(buf))
    {
        switch(select(fd+1,&readfds,NULL,NULL,&tv))
        {
        case -1: /* select error */
        case  0: /* time is out */
            return 0; break;
        default: break;
        }
        num=read(fd,buf+index,sizeof(buf)-index);
        index+=num;
        if(index<resLen) continue;
        if(!strncmp(buf+index-resLen,res,resLen))
            return 1; /* find */
    }
    return 0;
}



